﻿#include "CPanelLogger.h"

#include <QDateTime>
#include <QFile>
#include <QHBoxLayout>
#include <QLabel>
#include <QPushButton>
#include <QTextEdit>
#include <QVBoxLayout>

#include "global.h"

class CPanelLogger::CPanelLoggerPrivate
{
public:
    QTextEdit *view;

    CPanelLoggerPrivate(QWidget *parent) :
        view(new QTextEdit(parent))
    {
    }
};

CPanelLogger::CPanelLogger(QWidget *parent) :
    CPanelWidget(parent),
    p_(new CPanelLoggerPrivate(this))
{
    // layout
    QVBoxLayout *lay2 = new QVBoxLayout;
    lay2->addWidget(p_->view);
    lay2->setSpacing(0);
    lay2->setMargin(0);
    getContent()->setLayout(lay2);
    getHeaderButton(0)->hide();
    getHeaderButton(1)->show();
    getHeaderButton(1)->setText(tr("Clear"));
    setWindowTitle(tr("Logger"));

    // properties
    p_->view->setAcceptRichText(true);
    p_->view->setReadOnly(true);
    p_->view->setFontPointSize(14);

    // connect
    connect(getHeaderButton(1), &QPushButton::clicked, this, [this]() { p_->view->clear(); });
    connect(this, &CPanelLogger::messageNotify, this, &CPanelLogger::appendMessage,
            Qt::QueuedConnection);

    CLogger::add_observer(this);
}

CPanelLogger::~CPanelLogger()
{
}

void CPanelLogger::notify(int level, const std::string &msg)
{
    emit messageNotify(level, msg.c_str());
}

void CPanelLogger::appendMessage(int level, QString msg)
{
    QString message;
    auto dtstr = QDateTime::currentDateTime().toString("hh:mm:ss:zzz");
    switch (level)
    {
        case CLogger::ELoggerLevel_INFO:
            message = QString("<span style=\"font-size:14px;color:#333;\">INFO %1 : %2</span>").arg(dtstr).arg(msg);
            break;
        case CLogger::ELoggerLevel_WARN:
            message = QString("<span style=\"font-size:14px;color:#f0ad4e;\">WARN %1 : %2</span>")
                          .arg(dtstr)
                          .arg(msg);
            break;
        case CLogger::ELoggerLevel_ERROR:
            message = QString("<span style=\"font-size:14px;color:#d9534f;\">ERRO %1 : %2</span>")
                          .arg(dtstr)
                          .arg(msg);
            break;
        default:
            return;
    }
    // append to text edit
    p_->view->append(message);
}

void CPanelLogger::eventDeviceChanged(QString id)
{
    MSG(INFO) << tr("device changed: ") << id.toStdString();
}